package com.tom.architect.day10.simple2;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by hcDarren on 2017/9/24.
 */
public class PreferencesUtils {
    //region 单例模式
    private volatile static PreferencesUtils mInstance;
    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;
    private PreferencesUtils(){
    }
    public static PreferencesUtils getInstance(){
        if(mInstance == null){
            synchronized (PreferencesUtils.class){
                if(mInstance == null){
                    mInstance = new PreferencesUtils();
                }
            }
        }
        return mInstance;
    }
    //endregion

    // BaseApplication中全局初始化。
    public void init(Context context){
        // context.getApplicationContext() 上下文，避免内存泄漏。
        mPreferences = context.getApplicationContext().getSharedPreferences("cache",Context.MODE_PRIVATE);
        mEditor = mPreferences.edit();
    }
    public void commit(){
        mEditor.commit();
    }

    // 支持链式调用
    public PreferencesUtils saveString(String key,String value){
        mEditor.putString(key,value);
        return this;
    }

    public String getString(String key){
        return mPreferences.getString(key,"");
    }

}
